﻿using System;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;

using iPhoneUI.Shell;
using iPhoneUI.Widgets;

namespace iPhoneUI
{
    public static class WidgetFactory
    {
        public static Widget CreateWidget(IWidgetOwner owner, WidgetConfig config)
        {
            Debug.Assert(owner != null);
            Debug.Assert(config != null);

            Widget widget = Activator.CreateInstance(config.WidgetType) as Widget;
            Debug.Assert(widget != null);

            widget.SetProperties(config.Properties);

            widget.SnapStyle = config.SnapStyle;
            widget.SetOwner(owner);

            return widget;
        }

        public static void PlaceWidget(Rectangle rectangle, IEnumerable<Widget> widgets, Widget widget)
        {
            Rectangle free = GetFreeArea(rectangle, widgets);

            if (widget.SnapStyle == SnapStyle.Top)
                widget.ClientArea = new Rectangle(free.X, free.Y, free.Width, widget.Size.Height);

            else if (widget.SnapStyle == SnapStyle.Bottom)
                widget.ClientArea = new Rectangle(free.X, free.Bottom - widget.Size.Height, free.Width, widget.Size.Height);

            else if (widget.SnapStyle == SnapStyle.Fill)
                widget.ClientArea = free;
        }

        private static Rectangle GetFreeArea(Rectangle rectangle, IEnumerable<Widget> widgets)
        {
            foreach (Widget w in widgets.Where(w => w.SnapStyle != SnapStyle.None))
            {
                if (w.SnapStyle == SnapStyle.Top)
                    rectangle.Y = w.ClientArea.Bottom;

                rectangle.Height -= w.ClientArea.Height;
            }

            return rectangle;
        }
    }
}
